<template>
  <div class="data-maintenance">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据维护</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryForm" ref="queryFormRef" :inline="true">
        <el-form-item label="表计ID" prop="meter_id">
          <el-select clearable filterable style="width: 150px" placeholder="请选择表计" v-model="queryForm.meter_id">
            <el-option v-for="item in meterList" :key="item.id" :label="item.meter_code" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <CustomDatePicker v-model="queryForm.timeRange" :is-range="true" :max-days="90" :min-days="0" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 添加数据按钮 -->
      <div class="operation-container">
        <el-button type="primary" @click="handleAdd">添加数据</el-button>
      </div>

      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="读数ID" />
        <el-table-column prop="device_id" label="表计ID" />
        <el-table-column prop="value" label="读数">
          <template #default="{ row }">
            <el-input v-if="row.id === editingId" v-model="editingValue" @keyup.enter="handleSave" ref="editInput"
              :disabled="loading" />
            <span v-else>{{ row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="时间">
          <template #default="{ row }">
            {{ formatTime(row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <template v-if="row.id === editingId">
              <el-button type="success" size="small" @click="handleSave" :loading="loading">
                保存
              </el-button>
              <el-button type="info" size="small" @click="handleCancelEdit" :disabled="loading">
                取消
              </el-button>
            </template>
            <el-button v-else type="primary" size="small" @click="handleEdit(row)" :disabled="!!editingId">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <!-- 添加数据对话框 -->
      <el-dialog v-model="dialogVisible" title="添加数据" width="500px" :close-on-click-modal="false">
        <el-form :model="addForm" ref="addFormRef" label-width="80px" :rules="rules">
          <el-form-item label="表计" prop="meter_id">
            <el-select v-model="addForm.meter_id" placeholder="请选择表计" style="width: 100%" clearable filterable>
              <el-option v-for="item in meterList" :key="item.id" :label="item.meter_code" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="读数" prop="value">
            <el-input v-model.number="addForm.value" placeholder="请输入读数" />
          </el-form-item>
          <el-form-item label="时间" prop="time">
            <el-date-picker v-model="addForm.time" type="datetime" placeholder="选择日期时间" style="width: 100%"
              value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, watch } from "vue";
import { handleError } from "@/utils/handleError";
import {
  getRecordListApi,
  updateRecordApi,
  createRecordApi,
} from "@/api/record";
import { getMeterInfoApi } from "@/api/meter";
import { useCompanyStore } from "@/stores/company";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";

let companyStore = useCompanyStore();
// 查询表单ref
const queryFormRef = ref(null);
const editInput = ref(null);
const meterList = ref([]);
// 编辑状态
const editingId = ref(null);
const editingValue = ref("");

// 默认时间范围
const defaultTimeRange = [
  dayjs().subtract(6, 'day').startOf('day').valueOf(),
  dayjs().endOf('day').valueOf()
];

// 查询表单数据
const queryForm = reactive({
  meter_id: "",
  timeRange: [...defaultTimeRange],
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 添加数据相关
const dialogVisible = ref(false);
const addFormRef = ref(null);
const submitLoading = ref(false);

// 添加表单数据
const addForm = reactive({
  meter_id: "",
  value: "",
  time: "",
});

// 表单验证规则
const rules = {
  meter_id: [{ required: true, message: "请选择表计", trigger: "change" }],
  value: [
    { required: true, message: "请输入读数", trigger: "blur" },
    { type: "number", message: "读数必须为数字", trigger: "blur" },
  ],
  time: [{ required: true, message: "请选择时间", trigger: "change" }],
};

// 获取表格数据
const getTableData = async () => {
  // 如果没有选择表计，直接清空表格数据并返回
  if (!queryForm.meter_id) {
    tableData.value = [];
    pagination.total = 0;
    return;
  }

  try {
    loading.value = true;
    const params = {
      meter_id: queryForm.meter_id,
      start_time: queryForm.timeRange[0] || undefined,
      end_time: queryForm.timeRange[1] || undefined,
      offset: (pagination.currentPage - 1) * pagination.pageSize,
      limit: pagination.pageSize,
    };

    const res = await getRecordListApi(params);
    if (res.code === 200) {
      tableData.value = res.data;
      pagination.total = res.total;
    } else {
      ElMessage.error("获取数据失败");
    }
  } catch (error) {
    handleError(error, "获取数据失败", true);
  } finally {
    loading.value = false;
  }
};

// 开始编辑
const handleEdit = (row) => {
  editingId.value = row.id;
  editingValue.value = row.value;
  nextTick(() => {
    editInput.value?.focus();
  });
};
// 保存编辑
const handleSave = async () => {
  if (!editingValue.value) {
    ElMessage.warning("请输入读数值");
    return;
  }

  try {
    loading.value = true;
    const currentRow = tableData.value.find(
      (row) => row.id === editingId.value
    );

    // 格式化数值为数字类型且保留两位小数
    let formattedValue = Number(Number(editingValue.value).toFixed(2));
    if (formattedValue <= 0) {
      formattedValue = -1;
    }
    const updateData = {
      id: editingId.value,
      time: currentRow.time,
      value: formattedValue,
    };

    const type = meterList.value.find(
      (item) => item.id === currentRow.device_id
    ).type;

    await updateRecordApi(updateData, type);
    ElMessage.success("修改成功");

    // 取消编辑状态
    handleCancelEdit();

    // 刷新表格数据而不是更新本地数据
    await getTableData();
  } catch (error) {
    handleError(error, "修改数据失败", true);
  } finally {
    loading.value = false;
  }
};

// 取消编辑
const handleCancelEdit = () => {
  editingId.value = null;
  editingValue.value = "";
};

// 打开添加对话框
const handleAdd = () => {
  dialogVisible.value = true;
};

// 提交添加
const handleSubmit = async () => {
  if (!addFormRef.value) return;

  await addFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      submitLoading.value = true;

      // 获取选中表计的类型
      const selectedMeter = meterList.value.find(
        (item) => item.id === addForm.meter_id
      );

      if (!selectedMeter) {
        ElMessage.error("未找到选中的表计信息");
        return;
      }

      // 格式化数值为数字类型且保留两位小数
      const formattedValue = Number(Number(addForm.value).toFixed(2));

      const submitData = {
        device_id: addForm.meter_id,
        value: formattedValue,
        time: addForm.time,
      };

      await createRecordApi(submitData, selectedMeter.type);
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      // 选中表计
      queryForm.meter_id = addForm.meter_id;

      // 清空表单
      addFormRef.value.resetFields();

      // 刷新表格数据
      getTableData();
    } catch (error) {
      handleError(error, "添加数据失败", true);
    } finally {
      submitLoading.value = false;
    }
  });
};

// 搜索
const handleSearch = () => {
  handleCancelEdit();
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  handleCancelEdit();
  // 重置表单
  queryFormRef.value?.resetFields();
  // 重置时间范围为默认值
  queryForm.timeRange = [...defaultTimeRange];
  pagination.currentPage = 1;
  // 清空表格数据而不是立即查询
  tableData.value = [];
  pagination.total = 0;
};

// 分页大小改变
const handleSizeChange = (val) => {
  handleCancelEdit();
  pagination.pageSize = val;
  getTableData();
};

// 页码改变
const handleCurrentChange = (val) => {
  handleCancelEdit();
  pagination.currentPage = val;
  getTableData();
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return "";
  return new Date(time).toLocaleString();
};

// 对话框关闭时重置表单
watch(dialogVisible, (val) => {
  if (!val) {
    addFormRef.value?.resetFields();
  }
});

// 获取表计列表
async function getMeterList() {
  try {
    let company_id = companyStore.currentCompany.id;
    const res = await getMeterInfoApi({
      company_id: company_id,
    });
    meterList.value = res.data;
  } catch (error) {
    handleError(error, "获取表计列表失败");
  }
}

// 监听公司变化
watch(() => companyStore.currentCompany, (newVal, oldVal) => {
  // 只有在公司真正变化时才重置
  if (newVal && oldVal && newVal.id !== oldVal.id) {
    // 重置表单
    handleReset();
  }
  // 无论如何都要重新获取表计列表
  getMeterList();
}, {
  immediate: true,
  deep: true
});
</script>

<style scoped>
.data-maintenance {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>